package com.ruiyou.ub;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public class UVideoView extends RelativeLayout implements View.OnClickListener, View.OnTouchListener {

  private final ImageButton btnLock;
  private boolean locked = false;
  private Timer timerLock;
  private Activity activity;

  public UVideoView(Context context) {
    this(context, null);
    activity = (Activity) context;
  }

  @SuppressLint("ClickableViewAccessibility")
  public UVideoView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    // 利用布局文件填充View实例
    inflate(context, R.layout.layout_fullscreen, this);
    findViewById(R.id.video_cover).setOnTouchListener(this);
    btnLock = findViewById(R.id.ib_lock);
    btnLock.setOnClickListener(this);
    btnLock.setVisibility(GONE);
  }

  // 锁屏拦截
  @Override
  public boolean onTouch(View v, MotionEvent event) {
    int action = event.getAction();
    if ((action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_UP)) {
      if (timerLock != null) {
        timerLock.cancel();
        timerLock = null;
      }
      btnLock.setVisibility(View.VISIBLE);
      timerLock = new Timer();
      timerLock.schedule(new TimerTask() {
        @Override
        public void run() {
          activity.runOnUiThread(() -> btnLock.setVisibility(GONE));
        }
      }, 3000);
      return locked;
    }
    return false;
  }

  @Override
  public void onClick(View v) {
    if (v.getId() == btnLock.getId()) {
      locked = !locked;
      int imgId = locked ? R.drawable.ic_lock : R.drawable.ic_unlock;
      btnLock.setImageResource(imgId);
    }
  }
}
